package com.lzp.appexp

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 4/9/21
 */
fun main() {

    val test = Test1()
    val realfun = object : IFun {
        override fun doFun() {
            println("do fun")
        }
    }
    test.setFun(realfun)
    val method = test.javaClass.getMethod("setFun", IFun::class.java)

    val handle = ProxyHandle(realfun)
    val proxy = Proxy.newProxyInstance(test.javaClass.classLoader, arrayOf<Class<*>>(IFun::class.java), handle)
    method.invoke(test, proxy)
    test.doFun()
}

class Test1 {
    private var test: IFun? = null
    fun setFun(test: IFun) {
        this.test = test
    }

    fun doFun() {
        test?.doFun()
    }
}

interface IFun {
    fun doFun()
}

class ProxyHandle(private val target:Any) : InvocationHandler {
    override fun invoke(proxy: Any, method: Method?, args: Array<Any>?): Any? {
        println("do  =  ${method?.name} 前")
        method?.invoke(target, *args.orEmpty())
        println("do  =  ${method?.name} 后")
        return null
    }
}